#!/usr/bin/env python
# -*- coding: utf-8 -*-
#   
#       Copyright 2010 Santiago Lezica, Juan Pablo Orsay, Facundo Martinez.
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

# The current convention for Message Type IDs is:
#   a length 4 string in capital letters, formed by concatenating:
#       - a 3-letter combination describing the message.
#       - a single chr 'R' for Request, 'P' for response, 'N' for notification.

import os, inspect
from carcassonne.model import Handler, Message

class DispatcherHandler(Handler):

    def __init__(self):
        self._comm = None
        self._dao = None   
        self._handlers = {}
        self._messages = {}

    def config(self, comm, codec, dao, handlers, messages):
        self._comm = comm
        self._dao = dao
        self._codec = codec
    
        self._handlers = {}
        for hclass in handlers:
            hinstance = hclass()
            hinstance.dao = self._dao
            self._handlers[hclass.handle_type_id] = hinstance
        
        self._messages = {}
        for mclass in messages:
            self._messages[mclass.type_id] = mclass

    def handle(self, uid, data):

        dictionary = self._codec.decode(data)
        message = self._messages[dictionary["type_id"]]()
        message.loadd(dictionary)
        message.from_id = uid
        
        for response in self._handlers[message.type_id].handle(message):
            self._comm.sendData(response.to_id,
                                self._codec.encode(response.toDict()))
        
